create アクション
自作お出かけアプリ
Create place ボタンを押すことで新たなリクエストが投げられる。
http://localhost:3000/rails/info/routes
https://gyazo.com/6566811dad936998cb9929d7a00c9ad2
HTTP メソッドは POST
code:places_controller.rb
def create
@place = Place.new(place_params)
respond_to do |format|
if @place.save
format.html { redirect_to @place, notice: 'Place was successfully created.' }
format.json { render :show, status: :created, location: @place }
else
format.html { render :new }
format.json { render json: @place.errors, status: :unprocessable_entity }
end
end
end
1.リクエストのパラメータを使って Place のデータを作る
@place = Place.new(place_params)
Place.new メソッドに引数がある
place_params は controller に定義されているリクエストパラメータ。
Strong Parameters で変更を許可するパラメータを絞っている
2.Place データを保存する
if @place.save
Railsでデータを保存したあとの処理について
3a. 成功したら show 画面へ
format.html { redirect_to @place, notice: 'Place was successfully created.' }
format.json { render :show, status: :created, location: @place }
3b. 失敗したら元の new 画面へ
format.html { render :new }
format.json { render json: @place.errors, status: :unprocessable_entity }
モデル
1と2の new メソッドと save メソッドで保存する流れ
Place.new で Place モデルオブジェクトを作る。
モデル名は英語の単数形、大文字始まりのルールがある。
すべて小文字の place は変数名。
1つの Place オブジェクトが代入されるため単数形を使う。
@place.save で保存する。
#Railsの教科書を読んだ